/* eslint-disable */
/**
 * @Description: 幸运抽奖
 * @author ourslookAdmin
 * @date 2019-05-05 12:29:33
 */
import React, { Fragment } from 'react';
import {
  BackTop,
  Button,
  Card,
  Checkbox,
  Col,
  DatePicker,
  Divider,
  Form,
  Icon,
  Input,
  InputNumber,
  Radio,
  Select,
  Spin,
  Switch,
  Table,
  Tooltip,
  Upload,
} from 'antd';
import { formatMessage, FormattedMessage } from 'umi/locale';
import 'antd/dist/antd.css';
import PropTypes from 'prop-types';
import { connect } from 'dva';
import { requestLists, requestPromise } from '@/utils/request';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import BaseForm from '../../../components/ourslook/BaseForm';
import ETable from '../../../components/ourslook/ETable';
import { getWebPath } from '../../../utils/request';
import uiUtils, { hasPermission, rulesReg } from '../../../utils/uiUtils';
import styles from '../../../utils/ourslook.less';
import Modal from 'drag-modal';
import BraftEditor from 'braft-editor';
import 'braft-editor/dist/index.css';
import moment from 'moment';
import { handleEditorupload ,editorPreview, editorProps} from '../../../utils/braft_editor_config';
import Ellipsis from '../../../components/ourslook/Ellipsis';
import DefaultImage from '../../../components/ourslook/DefaultImage';

const FormItem = Form.Item;
const Option = Select.Option;
const RadioGroup = Radio.Group;
const TextArea = Input.TextArea;
const Password = Input.Password;
const CheckboxGroup = Checkbox.Group;
const { MonthPicker, RangePicker, WeekPicker } = DatePicker;

const getValue = obj =>
  Object.keys(obj)
    .map(key => obj[key])
    .join(',');

const drawType = {
  1: '时间',
  2: '人数',
  3: '转盘',
};
const drawStatus = {
  1: '已开奖',
  2: '未开奖',
  3: '开奖中',
};

/**
 * 奖品类型
 */
const giftType = {
  1: '积分',
  2: '现金',
  3: '实物',
  4: '电子券',
  5: '谢谢参与',
};

// @coming({title: '精彩即将呈现！', value: Date.now() + 1000 * 60 * 60 * 24 * 2})
@connect(() => ({}))
class PromotionDraw extends React.Component {
  params = {
    page: 1,
    limit: 10,
  };

  formItemLayout = {
    labelCol: { span: 5 },
    wrapperCol: { span: 19 },
  };

  /**
   * https://ant-design.gitee.io/components/table-cn/
   *
   * 需要指定 column 的 width 属性，否则列头和内容可能不对齐。（必须留一列不设宽度或者minWidth以适应弹性布局）
   * 建议指定 scroll.x 为大于表格宽度的固定值或百分比。注意，且非固定列宽度之和不要超过 scroll.x, 一般无table正常展开的宽度
   * 未知长度字段或者字符特别多的字段不要放置在列表
   */
  columns = [
    {
      title: '',
      width: 30,
      align: 'center',
      fixed: 'left',
      render: (value, record, index) => index + 1,
    },
    {
      title: '活动名称',
      dataIndex: 'name',
      // width: 120,
      align: 'center',
      sorter: false,
      key: 'name',
      render: value => (
        <Ellipsis length={10} tooltip>
          {value}
        </Ellipsis>
      ),
    },
    {
      title: '活动封面图片',
      dataIndex: 'image',
      width: 120,
      align: 'center',
      sorter: false,
      key: 'image',
      render: record => <DefaultImage src={record} width="100" />,
    },
    /* {
       title: '图文介绍',
       dataIndex: 'introduction',
       width: 120,
       align: 'center',
       sorter: false,
       key: 'introduction',
     },*/
    /*{
      title: '规则说明',
      dataIndex: 'rules',
      width: 120,
      align: 'center',
      sorter: false,
      key: 'rules',
    },*/
    {
      title: '类型',
      dataIndex: 'type',
      width: 120,
      align: 'center',
      sorter: false,
      key: 'type',
      render: val => {
        let type = '';
        if (val === 1) {
          type = '时间';
        } else if (val === 2) {
          type = '人数';
        } else if (val === 3) {
          type = '转盘';
        }
        return type;
      },
    },
    {
      title: '可参与次数(人/天)',
      dataIndex: 'canJoinCountByDay',
      width: 150,
      align: 'center',
      sorter: false,
      key: 'can_join_count_by_day',
    },
    {
      title: '有效期开始',
      dataIndex: 'validTimeStart',
      width: 120,
      align: 'center',
      sorter: false,
      key: 'valid_time_start',
    },
    {
      title: '有效期结束',
      dataIndex: 'validTimeEnd',
      width: 120,
      align: 'center',
      sorter: false,
      key: 'valid_time_end',
    },
    // {
    //   title: '抽奖状态',
    //   dataIndex: 'isOpenDraw',
    //   width: 80,
    //   align: 'center',
    //   sorter: false,
    //   fixed: 'right',
    //   key: 'is_open_draw',
    //   render: val => {
    //     let type = '';
    //     if (val === 1) {
    //       type = '已开奖';
    //     } else if (val === 2) {
    //       type = '未开奖';
    //     } else if (val === 3) {
    //       type = '开奖中';
    //     }
    //     return type;
    //   },
    // },
    {
      title: '状态',
      dataIndex: 'status',
      width: 80,
      align: 'center',
      sorter: false,
      fixed: 'right',
      key: 'status',
      render: (value, record, index) => (
        <React.Fragment>
          <div>
            <Switch
              checkedChildren="启用"
              unCheckedChildren="禁用"
              onChange={val => {
                this.setStateByTableColume(record, index);
                this.updateStatus(val);
              }}
              checked={value === 1}
            />
          </div>
        </React.Fragment>
      ),
    },
    {
      title: '操作',
      dataIndex: '',
      width: 120,
      align: 'center',
      fixed: 'right',
      render: (value, record, index) => (
        <React.Fragment>
          <a
            onClick={() => {
              this.setStateByTableColume(record, index);
              this.update();
            }}
          >
            <Tooltip title={<FormattedMessage id="ours.curd.list.edit" defaultMessage="编辑" />}>
              <Icon type="edit" />
            </Tooltip>
          </a>
          <Divider type="vertical" />
          <a
            onClick={() => {
              this.setStateByTableColume(record, index);
              this.view();
            }}
          >
            <Tooltip title={<FormattedMessage id="ours.curd.list.info" defaultMessage="查看" />}>
              <Icon type="info" />
            </Tooltip>
          </a>
        </React.Fragment>
      ),
    },
  ];

  constructor(props) {
    super(props);
    this.state = {
      showList: 1, //1:显示列表、2:显示新增
      formList: PromotionDraw.getFormList(),
      selectedRows: [],
      selectedIds: [],
      selectedIndexs: [],
      editModalTitle: null,
      editModalType: null,
      editModel: null,
      editModelConfirmLoading: false,
      //其他属性下面书写
      contentHtml: BraftEditor.createEditorState(''),
    };
  }

  // 筛选条件
  static getFormList = () => [
    {
      type: 'INPUT',
      field: 'name',
      label: '抽奖活动名称',
      placeholder: '抽奖活动名称',
    },
  ];

  componentDidMount() {
    this.requestList();
  }

  componentWillUnmount() {}

  /**
   * 根据 formItem field 取值 查找formItem
   * @param formItemField obj的field字段
   * @returns 一个对象
   */
  findFormListItemByField = formItemField =>
    this.state.formList.find((value, index, array) => value.field === formItemField);

  query = fieldParams => {
    this.params = JSON.parse(JSON.stringify(Object.assign(this.params, fieldParams)));
    this.requestList();
  };

  add = () => {
    this.setState({
      editModalType: 'add',
      editModalTitle: formatMessage({ id: 'ours.curd.list.create' }), //创建
      editModel: {},
      showList: 2,
      contentHtml: BraftEditor.createEditorState(''),
    });
  };

  update = () => {
    const { selectedRows, selectedIds, selectedIndexs } = this.state;
    if (!selectedRows) {
      uiUtils.showAlert(formatMessage({ id: 'ours.curd.show-alert.select-please' }));
      return;
    }
    if (selectedRows.length > 1) {
      uiUtils.showAlert(formatMessage({ id: 'ours.curd.show-alert.select-one-please' }));
      return;
    }
    this.setState({
      editModalType: 'update',
      editModalTitle: <FormattedMessage id="ours.curd.list.edit" defaultMessage="编辑" />,
      editModel: JSON.parse(JSON.stringify(selectedRows[0])),
      showList: 2,
      contentHtml: BraftEditor.createEditorState(selectedRows[0].introduction),
    });
    this.getInfo(selectedRows[0].id);
  };

  view = () => {
    const { selectedRows, selectedIds, selectedIndexs } = this.state;
    if (!selectedRows) {
      uiUtils.showAlert(formatMessage({ id: 'ours.curd.show-alert.select-please' }));
      return;
    }
    if (selectedRows.length > 1) {
      uiUtils.showAlert(formatMessage({ id: 'ours.curd.show-alert.select-one-please' }));
      return;
    }
    this.setState({
      editModalType: 'view',
      editModalTitle: <FormattedMessage id="ours.curd.list.info" defaultMessage="查看" />,
      editModel: selectedRows[0],
      showList: 2,
      contentHtml: BraftEditor.createEditorState(selectedRows[0].introduction),
    });
    this.getInfo(selectedRows[0].id);
  };

  del = () => {
    const selectedRows = this.state.selectedRows;
    const ids = [];
    for (let i = 0; i < selectedRows.length; i += 1) {
      ids.push(selectedRows[i].id);
    }

    uiUtils.showConfirm(formatMessage({ id: 'ours.curd.show-alert.confirm-delete' }), () => {
      this.setState({
        loading: true,
      });
      requestPromise(`${getWebPath()}promotiondraw/delete`, {
        method: 'POST',
        body: ids,
      }).then(res => {
        this.setState({
          loading: false,
        });
        if (res && res.code === 0) {
          uiUtils.showMessage(
            formatMessage({ id: 'ours.curd.show-alert.operate-success' }),
            'success'
          );
          this.requestList();
        }
      });
    });
  };

  saveOrUpdate = () => {
    const editModalType = this.state.editModalType;
    console.log('这是saveOrUpdate方法');
    console.log(editModalType);
    console.log(this.editForm.state.willSelectGiftVisible);
    //不能双向绑定，这里只能原对象、新对象进行合并.
    const promotionDraw = Object.assign(
      this.state.editModel,
      this.editForm.props.form.getFieldsValue()
    );

    promotionDraw.giftEntityList = this.editForm.state.giftDataSources;
    promotionDraw.introduction = this.editForm.state.contentHtml.toHTML();

    this.editForm.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        // submit the values
        const url = promotionDraw.id == null ? '/promotiondraw/save' : '/promotiondraw/update';
        this.setState({
          editModelConfirmLoading: true,
        });
        promotionDraw.validTimeStart = `${promotionDraw.validTime[0].format(
          'YYYY-MM-DD'
        )} 00:00:00`;
        promotionDraw.validTimeEnd = `${promotionDraw.validTime[1].format('YYYY-MM-DD')} 23:59:59`;
        delete promotionDraw.validTime;

        requestPromise(getWebPath() + url, {
          method: 'POST',
          body: promotionDraw,
        }).then(res => {
          this.setState({
            editModelConfirmLoading: false,
          });
          if (res && res.code === 0) {
            uiUtils.showMessage(
              formatMessage({ id: 'ours.curd.show-alert.operate-success' }),
              'success'
            );
            this.setState({
              showList: 1,
            });

            //新增重新置为第一页
            if (!promotionDraw.id) {
              this.params.page = 1;
            }
            this.requestList();
          }
        });
      }
    });
  };

  getInfo = id => {};

  setStateByTableColume = (record, index) => {
    this.state = {
      ...this.state,
      selectedRows: [record],
      selectedIds: [record.id],
      selectedIndexs: [index],
    };
  };

  updateStatus = val => {
    const { selectedRows, selectedIds, selectedIndexs } = this.state;
    if (!selectedRows) {
      uiUtils.showAlert(formatMessage({ id: 'ours.curd.show-alert.select-please' }));
      return;
    }
    if (selectedRows.length > 1) {
      uiUtils.showAlert(formatMessage({ id: 'ours.curd.show-alert.select-one-please' }));
      return;
    }
    let status;
    if (val) {
      status = 1;
    } else {
      status = -1;
    }
    const ids = [];
    for (let i = 0; i < selectedRows.length; i += 1) {
      ids.push(selectedRows[i].id);
    }

    this.setState({
      loading: true,
    });
    //const data = 'modelIds=' + ids.join(',') + '&status=' + status;
    const data = {
      modelIds: ids.join(','),
      status,
    };
    requestPromise(`${getWebPath()}promotiondraw/operatePromotionDrawByIds`, {
      method: 'POST',
      contentType: 'application/x-www-form-urlencoded',
      body: data,
    }).then(res => {
      this.setState({
        loading: false,
      });
      if (res && res.msg === '1001') {
        uiUtils.showMessage('当前系统中上架的活动只能有一个', 'warning');
      } else if (res && res.msg === '1002') {
        uiUtils.showMessage('id不能为空！', 'warning');
      } else {
        if (res && res.code === 0) {
          uiUtils.showMessage(
            formatMessage({ id: 'ours.curd.show-alert.operate-success' }),
            'success'
          );
        }
      }
      this.requestList();
    });
  };

  //========其他所有的处理方法，请在按照约定进行处理==========

  /**
   * 表格 筛选和排序 回调
   */
  filtersSorterChange = tableParams => {
    this.params = JSON.parse(JSON.stringify(Object.assign(this.params, tableParams)));
    this.requestList();
  };

  requestList = () => {
    requestLists(this, `${getWebPath()}promotiondraw/listVo`, this.params);
  };

  vShow = showListNum => ({ display: this.state.showList === showListNum ? 'block' : 'none' });

  render() {
    const style = {
      style: {
        marginLeft: 10,
        marginTop: 10,
      },
      disabled: this.state.selectedIndexs.length <= 0,
    };

    /* eslint-disable react/jsx-no-bind */
    return (
      <PageHeaderWrapper title="">
        <Card
          bordered={false}
          style={{ ...this.vShow(1) }}
          className={styles.oursCard}
          bodyStyle={{ padding: '20px' }}
        >
          <BaseForm
            formList={this.state.formList}
            loading={this.state.loading}
            filterSubmit={this.query}
          />

          <Fragment>
            <Button
              type="primary"
              icon="plus"
              onClick={this.add}
              hidden={!hasPermission('promotiondraw:save')}
            >
              <FormattedMessage id="ours.curd.list.add" defaultMessage="新增" />
            </Button>

            <Button
              type="danger"
              icon="delete"
              {...style}
              onClick={this.del}
              hidden={!hasPermission('promotiondraw:delete')}
            >
              <FormattedMessage id="ours.curd.list.delete" defaultMessage="删除" />
            </Button>
          </Fragment>

          <div className="content-wrap">
            <ETable
              onSelectRow={uiUtils.onSelectRow.bind(this)}
              primaryKey="id"
              selectedRows={this.state.selectedRows}
              selectedIds={this.state.selectedIds}
              selectedIndexs={this.state.selectedIndexs}
              onChange={this.filtersSorterChange}
              columns={this.columns}
              dataSource={this.state.list}
              pagination={this.state.pagination}
              loading={this.state.loading}
              scroll={{ x: 950 }}
            />
          </div>
        </Card>

        <BackTop />

        <Spin spinning={this.state.editModelConfirmLoading} delay={10}>
          {//返回null,这里对不用的组件进行销毁
          this.state.showList === 1 ? null : (
            <Card
              title={this.state.editModalTitle}
              bordered={false}
              actions={[
                <div>
                  <React.Fragment>
                    <Button
                      type="primary"
                      hidden={this.state.editModalType === 'view'}
                      style={{ marginRight: '18px' }}
                      onClick={this.saveOrUpdate}
                    >
                      <FormattedMessage id="ours.curd.add.save" defaultMessage="保存" />
                    </Button>
                    <Button
                      style={{ marginRight: '18px' }}
                      onClick={() => {
                        this.editForm.props.form.resetFields();
                        this.setState({ showList: 1 });
                      }}
                    >
                      <FormattedMessage id="ours.curd.add.back" defaultMessage="返回" />
                    </Button>
                  </React.Fragment>
                </div>,
              ]}
              style={{ ...this.vShow(2) }}
              bodyStyle={{ padding: '20px' }}
              ref={node => {
                this.container = node;
              }}
            >
              <EditForm
                type={this.state.editModalType}
                model={this.state.editModel}
                contentHtml={this.state.contentHtml}
                wrappedComponentRef={inst => {
                  this.editForm = inst;
                }}
              />
            </Card>
          )}
        </Spin>
      </PageHeaderWrapper>
    );
  }
}

export default PromotionDraw;

/**
 * 添加奖品form
 */
@Form.create()
class DrawGiftForm extends React.Component {
  static propTypes = {
    visible: PropTypes.bool,
    onCancel: PropTypes.func,
    onOk: PropTypes.func,
  };

  static defaultProps = {
    visible: false,
    onCancel: () => {},
    onOk: () => {},
  };

  constructor(props) {
    super(props);
    const defaultRewardImageFileList = null;
    this.state = {
      rewardType: giftType[3], //默认实物
      previewVisible: false, //上传文件预览
      previewImage: '', //上传文件预览
      defaultRewardImageFileList, //上传文件列表
      fileImgList:
        defaultRewardImageFileList && defaultRewardImageFileList.length > 0
          ? [defaultRewardImageFileList[0]]
          : [],
    };
  }

  handleUploadImgOnRemove = file => {
    //只上传一文件，这里偷懒
    this.setState({
      fileImgList: [],
      defaultRewardImageFileList: null,
    });
  };

  //抽奖图片
  handleUploadOnChangeDrawGift = info => {
    const { loadingCallback } = this.props;
    // 状态有：uploading done error removed
    if (info.file.status === 'done') {
      //这个Upload组件比较特殊，这里在OnChange方法手工设置value,不做延迟，就设置不了被覆盖了。
      const response = info.fileList[0].response;
      this.setState({
        fileImgList: info.fileList,
      });
      if (response) {
        if (response.code === 0) {
          uiUtils.showMessage(`${info.file.name} 文件上传成功.`, 'success');
          setTimeout(() => {
            // console.log(response.object);
            this.props.form.setFieldsValue({
              rewardImage: response.object,
            });
            if (loadingCallback) {
              loadingCallback(false);
            }
          }, 500);
        } else {
          uiUtils.showAlert(response.msg, 'error');
          if (loadingCallback) {
            loadingCallback(false);
          }
        }
      }
    } else if (info.file.status === 'error') {
      if (loadingCallback) {
        loadingCallback(false);
      }
      uiUtils.showMessage(`${info.file.name} 文件上传失败.`, 'error');
    } else if (info.file.status === 'uploading') {
      if (loadingCallback) {
        loadingCallback(true);
      }
    }
  };
  /**
   * 奖品类型发生改变
   * @param val
   */
  rewardTypeChange = val => {
    // console.log(val);
    this.state.rewardType = giftType[val];
  };

  //奖品选择 (搜索，礼品表或者优惠券表)
  giftSearch = value => {
    //如果是实物，
    if (this.state.rewardType === giftType[3]) {
      requestPromise(
        `${getWebPath(
          `/promotiongift/list?status=1&giftName=${value === undefined ? '' : value}`
        )}`,
        {
          method: 'GET',
        }
      ).then(res => {
        if (res && res.code === 0) {
          const datas = res.page.list || [];
          const results = [];
          datas.forEach(r => {
            results.push(<Option key={r.id}>{r.giftName}</Option>);
          });
          this.setState({
            giftChildren: results,
          });
        }
      });
    }
    //优惠券
    else if (this.state.rewardType === giftType[4]) {
      requestPromise(
        `${getWebPath(`/mailcoupon/list?status=1&title=${value === undefined ? '' : value}`)}`,
        {
          method: 'GET',
        }
      ).then(res => {
        if (res && res.code === 0) {
          const datas = res.page.list || [];
          const results = [];
          datas.forEach(r => {
            results.push(<Option key={r.id}>{r.title}</Option>);
          });
          this.setState({
            giftChildren: results,
          });
        }
      });
    }
  };

  render() {
    const visible = this.props.visible;
    const onCancel = this.props.onCancel;
    const onOk = this.props.onOk;
    const model = this.props.model || {};
    const {
      form,
      form: { getFieldDecorator, getFieldValue, setFieldsValue },
    } = this.props;
    const formItemLayout = {
      labelCol: { span: 5 },
      wrapperCol: { span: 18 }, //5+19=24,少一个栅格
    };
    const colSpanLayout = { md: 12, sm: 24 }; //每一col跨?列

    const result = [];
    /*文件上传*/
    const uploadPropsDrawGift = {
      action: `${getWebPath('/api/fileUpload')}`,
      name: 'myfile',
      data: { moduleName: 'draw', isImage: true , acceptFileExts: 'image'},
      withCredentials: true,
      headers: {
        authorization: 'authorization-text',
      },
      onChange: this.handleUploadOnChangeDrawGift,
      onRemove: this.handleUploadImgOnRemove,
      defaultFileList: this.state.defaultRewardImageFileList,
      multiple: false,
      accept: '.jpg, .jpeg, .png, .bmp, ', //image/*
    };
    const uploadButton = (
      <div>
        <Icon type="plus" />
        <div className="ant-upload-text">上传</div>
      </div>
    );

    return (
      <Modal
        title="添加奖品"
        width={1000}
        visible={visible}
        onCancel={() => {
          this.setState({ previewImage: null });
          onCancel();
        }}
        onOk={() => {
          this.setState({ previewImage: null });
          this.props.form.validateFieldsAndScroll((err, values) => {
            if (!err) {
              //这里保存审核结果
              const gift = Object.assign(model, this.props.form.getFieldsValue());
              onOk(gift);
            }
          });
        }}
      >
        <Card bordered hoverable bodyStyle={{ paddingBottom: 10 }} style={{ marginBottom: 20 }}>
          <Col {...colSpanLayout}>
            <FormItem label="奖品类型" {...formItemLayout}>
              {getFieldDecorator('rewardType', {
                initialValue: model.rewardType === undefined ? 3 : model.rewardType,
                rules: [],
              })(
                <Select
                  placeholder="请选择"
                  onChange={this.rewardTypeChange}
                  style={{ width: 120 }}
                >
                  <Option value={3}>实物</Option>
                  <Option value={4}>电子券</Option>
                </Select>
              )}
            </FormItem>
          </Col>
          <Col {...colSpanLayout}>
            <FormItem label="奖品取值" {...formItemLayout}>
              {getFieldDecorator('rewardValueId', {
                initialValue: model.rewardValueId,
                rules: [],
              })(
                <Select
                  showSearch
                  style={{ width: 315 }}
                  placeholder="请选择"
                  optionFilterProp="children"
                  onFocus={this.giftSearch}
                  onSearch={this.giftSearch}
                  notFoundContent={null}
                >
                  {result}
                  {this.state.giftChildren}
                </Select>
              )}
              &nbsp;&nbsp;
              {
                <Tooltip placement="right" title="奖品类型为实物是选择的是礼品，否则是优惠券">
                  <Icon type="question-circle" />
                </Tooltip>
              }
            </FormItem>
          </Col>
          <Col {...colSpanLayout}>
            <FormItem label="奖品名称" {...formItemLayout}>
              {getFieldDecorator('rewardName', {
                initialValue: model.rewardName,
                rules: [
                  {
                    required: true,
                    message: '奖品名称必填',
                  },
                  {
                    whitespace: true,
                    message: '不能包含空白符',
                  },
                  {
                    max: 32,
                    message: '最长32个字符',
                  },
                ],
              })(<Input type="text" autocomplete="off" maxlength={32} placeholder="奖品名称" />)}
            </FormItem>
          </Col>
          <Col {...colSpanLayout}>
            <FormItem
              extra="支持png、jpg、gif, 大小不超过3MB, 视频资源图片推荐尺寸：210 x 231 ;"
              label="奖品图片"
              {...formItemLayout}
            >
              {getFieldDecorator('rewardImage', {
                initialValue: model.rewardImage,
                rules: [
                  {
                    required: true,
                    message: '奖品图片必须有',
                  },
                ],
              })(
                <div className="clearfix">
                  <Upload {...uploadPropsDrawGift} listType="picture-card">
                    {this.state.fileImgList && this.state.fileImgList.length >= 1
                      ? null
                      : uploadButton}
                  </Upload>
                  <Modal
                    visible={this.state.previewVisible}
                    footer={null}
                    onCancel={() => this.setState({ previewVisible: false })}
                  >
                    <img alt="imgExample" style={{ width: '100%' }} src={this.state.previewImage} />
                  </Modal>
                </div>
              )}
            </FormItem>
          </Col>
          <Col {...colSpanLayout}>
            <FormItem label="奖品数量" {...formItemLayout}>
              {getFieldDecorator('rewardNum', {
                initialValue: model.rewardNum,
                rules: [
                  {
                    required: true,
                    message: '奖品数量必填',
                  },
                  rulesReg('busInt'),
                ],
              })(<InputNumber min={1} max={999999} autocomplete="off" placeholder="奖品数量" />)}
            </FormItem>
          </Col>
          <Col {...colSpanLayout}>
            <FormItem label="中奖概率(%)" {...formItemLayout}>
              {getFieldDecorator('rewardRate', {
                initialValue: model.rewardRate,
                rules: [
                  {
                    required: true,
                    message: '中奖概率必填',
                  },
                  rulesReg('startWeigt'),
                ],
              })(<InputNumber min={0} max={100} autocomplete="off" placeholder="中奖概率" />)}
              &nbsp;&nbsp;
              <Tooltip placement="right" title="所有奖品的概率加起来不能大于100%">
                <Icon type="question-circle" />
              </Tooltip>
            </FormItem>
          </Col>
          <Col {...colSpanLayout}>
            <FormItem label="中奖提示语" {...formItemLayout}>
              {getFieldDecorator('rewardTip', {
                initialValue: model.rewardTip,
                rules: [
                  {
                    required: true,
                    message: '中奖提示语必填',
                  },
                  {
                    whitespace: true,
                    message: '不能包含空白符',
                  },
                  {
                    max: 1024,
                    message: '最长1024个字符',
                  },
                ],
              })(
                <Input type="text" autocomplete="off" maxlength={1024} placeholder="中奖提示语" />
              )}
            </FormItem>
          </Col>
        </Card>
      </Modal>
    );
  }
}

/**
 *  新增、编辑、复制、查看的Form
 */

/* eslint react/no-multi-comp:0 */
class EditForm extends React.Component {
  static propTypes = {
    type: PropTypes.string, //form类型，可选值：add（增加）、update（修改）、copy（复制）、view（查看）、
    model: PropTypes.object, //数据模型model，对应后台的model
    contentHtml: PropTypes.object,
  };

  static defaultProps = {
    type: '', //表单布局数组
    model: null,
    // eslint-disable-next-line
    contentHtml: BraftEditor.createEditorState(''),
  };

  constructor(props) {
    super(props);
    const defaultFileList = this.props.model.image
      ? [
          {
            uid: '1',
            name: '',
            status: 'done',
            url: this.props.model.image,
          },
        ]
      : null;

    this.state = {
      giftDataSources: this.props.model.giftEntityList,
      previewVisible: false, //上传文件预览
      previewImage: '', //上传文件预览
      defaultFileList, //上传文件列表
      fileList: defaultFileList && defaultFileList.length > 0 ? [defaultFileList[0]] : [],
    };
  }

  /**
   * 生命周期-属性发生变化...componentWillReceiveProps
   * 这里的nextProps，可以获取到所有的属性。
   * 目前没用，因为 dialog 每次都被销毁了
   */
  componentWillReceiveProps(nextProps) {}

  getPropsByKey = prop => {
    const model = this.props.model || {};
    const finalModel = Object.assign(model, this.props.form.getFieldsValue());
    return finalModel[prop];
  };

  handleUploadOnRemove = file => {
    this.setState({
      fileList: [],
      defaultFileList: null,
    });
  };

  handleUploadOnChange = info => {
    const { loadingCallback } = this.props;
    // 状态有：uploading done error removed
    if (info.file.status === 'done') {
      //这个Upload组件比较特殊，这里在OnChange方法手工设置value,不做延迟，就设置不了被覆盖了。
      const response = info.fileList[0].response;
      this.setState({
        fileList: info.fileList,
      });
      if (response) {
        if (response.code === 0) {
          uiUtils.showMessage(`${info.file.name} 文件上传成功.`, 'success');
          setTimeout(() => {
            // console.log(response.object);
            this.props.form.setFieldsValue({
              image: response.object,
            });
            if (loadingCallback) {
              loadingCallback(false);
            }
          }, 500);
        } else {
          uiUtils.showAlert(response.msg, 'error');
          if (loadingCallback) {
            loadingCallback(false);
          }
        }
      }
    } else if (info.file.status === 'error') {
      if (loadingCallback) {
        loadingCallback(false);
      }
      uiUtils.showMessage(`${info.file.name} 文件上传失败.`, 'error');
    } else if (info.file.status === 'uploading') {
      if (loadingCallback) {
        loadingCallback(true);
      }
    }
  };

  preview = () => {
    editorPreview(this.state.contentHtml.toHTML());
  };

  render() {
    const type = this.props.type; //编辑是：新增（add）、编辑(edit)、复制(copy)、还是查看(view)
    const model = this.props.model || {};
    const {
      form,
      form: { getFieldDecorator, getFieldValue, setFieldsValue },
    } = this.props;
    const formItemLayout = {
      labelCol: { span: 5 },
      wrapperCol: { span: 18 }, //5+19=24,少一个栅格
    };
    const colSpanLayout = { md: 12, sm: 24 }; //每一col跨?列
    const rowGutterPxLayout = { md: 24, sm: 16 }; //col之间的间隔?px
    const inputCodeDisabled = {
      disabled: type === 'update',
    };

    const braftEditorLayout = { md: 30, sm: 20 };

    /*文件上传*/
    const uploadProps = {
      action: `${getWebPath('/api/fileUpload')}`,
      name: 'myfile',
      data: { moduleName: 'draw', isImage: true, acceptFileExts: 'image' },
      withCredentials: true,
      headers: {
        authorization: 'authorization-text',
      },
      onChange: this.handleUploadOnChange,
      onRemove: this.handleUploadOnRemove,
      defaultFileList: this.state.defaultFileList,
      multiple: false,
      accept: '.jpg, .jpeg, .png, .bmp, ', //image/*
    };

    const uploadButton = (
      <div>
        <Icon type="plus" />
        <div className="ant-upload-text">上传</div>
      </div>
    );

    const result = [];
    if (type === 'update' || type === 'view') {
      result.push(
        <Option key={model.rewardValueId} value={model.rewardValueId}>
          {model.rewardName}
        </Option>
      );
    }

    let giftColumns = [
      {
        title: '奖品类型',
        dataIndex: 'rewardType',
        align: 'center',
        sorter: false,
        width: 100,
        key: 'reward_type',
        render: val => giftType[val],
      },
      {
        title: '奖品名称',
        dataIndex: 'rewardName',
        align: 'center',
        sorter: false,
        width: 200,
        key: 'reward_name',
      },
      {
        title: '奖品图片',
        dataIndex: 'rewardImage',
        align: 'center',
        width: 120,
        sorter: false,
        key: 'reward_image',
        render: record => <DefaultImage src={record}/>,
      },
      {
        title: '奖品数量',
        dataIndex: 'rewardNum',
        align: 'center',
        sorter: false,
        width: 100,
        key: 'reward_num',
      },
      {
        title: '中奖概率单位（%）',
        dataIndex: 'rewardRate',
        align: 'center',
        sorter: false,
        width: 100,
        key: 'reward_rate',
      },
      {
        title: '中奖提示语',
        dataIndex: 'rewardTip',
        align: 'center',
        sorter: false,
        key: 'reward_tip',
      },
      {
        title: '操作',
        key: '',
        dataIndex: '',
        width: 100,
        fixed: 'right',
        render: (value, record, index) => (
          <React.Fragment>
            <a
              hidden={this.props.type === 'view'}
              onClick={() => {
                if (type === 'view') {
                  console.log('这是查看哦！');
                } else {
                  let datasources = this.state.giftDataSources;
                  if (datasources === undefined) {
                    datasources = [];
                  }
                  let newdataSources = [];
                  for (let i = 0; i < datasources.length; i++) {
                    if (i !== index) {
                      newdataSources.push(datasources[i]);
                    }
                  }
                  //datasources.filter(item => item.id !== record.id)
                  this.setState({
                    giftDataSources: newdataSources,
                  });
                }
                console.log(value);
                console.log(record);
              }}
            >
              <Tooltip
                title={<FormattedMessage id="ours.curd.list.delete" defaultMessage="删除" />}
              >
                <Icon type="delete" />
              </Tooltip>
            </a>
          </React.Fragment>
        ),
      },
    ];

    const editorProps = {
      height: 500,
      media: {
        uploadFn: handleEditorupload,
      },
      imageControls: [],
      fontFamilies: [],
    };

    const extendControls = [
      {
        key: 'custom-button',
        type: 'button',
        text: '预览',
        onClick: this.preview,
      },
    ];

    return (
      <Fragment>
        <Form layout="horizontal">
          {/*活动基本信息*/}
          <Card
            bordered
            hoverable
            size="small"
            bodyStyle={{ paddingBottom: 10 }}
            style={{ marginBottom: 20 }}
            title="活动信息"
          >
            <Col {...colSpanLayout}>
              <FormItem label="活动名称" {...formItemLayout}>
                {type === 'view'
                  ? model.name
                  : getFieldDecorator('name', {
                      initialValue: model.name,
                      rules: [
                        {
                          required: true,
                          message: '抽奖活动名称必填',
                        },
                        {
                          whitespace: true,
                          message: '不能包含空白符',
                        },
                        {
                          max: 128,
                          message: '最长128个字符',
                        },
                      ],
                    })(
                      <Input
                        type="text"
                        autocomplete="off"
                        {...inputCodeDisabled}
                        maxlength={128}
                        placeholder="抽奖活动名称"
                      />
                    )}
              </FormItem>
            </Col>
            <Col {...colSpanLayout}>
              <FormItem
                extra="支持png、jpg、gif, 大小不超过3MB, 视频资源图片推荐尺寸：750 x  418"
                label="活动封面"
                {...formItemLayout}
              >
                {type === 'view' ? (
                  <img alt="" width={80} src={model.image} />
                ) : (
                  getFieldDecorator('image', {
                    initialValue: model.image,
                    rules: [
                      {
                        required: true,
                        message: '请上传抽奖活动封面图片',
                      },
                    ],
                  })(
                    <div className="clearfix">
                      <Upload {...uploadProps} listType="picture-card">
                        {this.state.fileList && this.state.fileList.length >= 1
                          ? null
                          : uploadButton}
                      </Upload>
                      <Modal
                        visible={this.state.previewVisible}
                        footer={null}
                        onCancel={() => this.setState({ previewVisible: false })}
                      >
                        <img
                          alt="imgExample"
                          style={{ width: '100%' }}
                          src={this.state.previewImage}
                        />
                      </Modal>
                    </div>
                  )
                )}
              </FormItem>
            </Col>
            <Col {...colSpanLayout}>
              <FormItem label="排序" {...formItemLayout}>
                {type === 'view'
                  ? model.sort
                  : getFieldDecorator('sort', {
                      initialValue: model.sort === undefined ? 1 : model.sort,
                      rules: [
                        {
                          required: true,
                          message: '排序必填',
                        },
                        rulesReg('number'),
                      ],
                    })(<InputNumber min={1} max={999999} autocomplete="off"  placeholder="排序" />)}
                &nbsp;&nbsp;
                <Tooltip placement="right" title="排序默认为从大到小(降序)">
                  <Icon type="question-circle" />
                </Tooltip>
              </FormItem>
            </Col>
            <Col {...colSpanLayout}>
              <FormItem label="规则说明" {...formItemLayout}>
                {type === 'view'
                  ? model.rules
                  : getFieldDecorator('rules', {
                      initialValue: model.rules,
                      rules: [
                        {
                          required: true,
                          message: '抽奖规则说明必填',
                        },
                        {
                          whitespace: true,
                          message: '不能包含空白符',
                        },
                        {
                          max: 65535,
                          message: '最长65535个字符',
                        },
                      ],
                    })(
                      <TextArea
                        autosize={{ minRows: 3, maxRows: 10 }}
                        maxlength={65535}
                        placeholder="抽奖规则说明"
                      />
                    )}
              </FormItem>
            </Col>
            <Col {...colSpanLayout}>
              <FormItem label="类型" {...formItemLayout}>
                {type === 'view'
                  ? drawType[model.type]
                  : getFieldDecorator('type', {
                      initialValue: model.type === undefined ? 3 : model.type,
                      rules: [
                        {
                          required: true,
                          message: '类型必填',
                        },
                      ],
                    })(
                      <Select placeholder="请选择" style={{ width: 120 }}>
                        {/* <Option value={1} disabled={true}>
                        时间
                      </Option>
                      <Option value={2} disabled={true}>
                        人数
                      </Option>*/}
                        <Option value={3}>转盘</Option>
                      </Select>
                    )}
              </FormItem>
            </Col>
            <Col {...colSpanLayout}>
              <FormItem label="可参与次数" {...formItemLayout}>
                {type === 'view'
                  ? model.canJoinCountByDay
                  : getFieldDecorator('canJoinCountByDay', {
                      initialValue: model.canJoinCountByDay,
                      rules: [
                        {
                          required: true,
                          message: '可参与次数必填',
                        },
                        rulesReg('number'),
                      ],
                    })(
                      <InputNumber
                        min={1}
                        max={10000}
                        style={{ width: 150 }}
                        autocomplete="off"
                        placeholder="可参与次数(人/天)"
                      />
                    )}
                &nbsp;&nbsp;
                <Tooltip placement="right" title="每个用户每天可以抽奖的总次数。">
                  <Icon type="question-circle" />
                </Tooltip>
              </FormItem>
            </Col>
            <Col {...colSpanLayout}>
              <FormItem label="有效期" {...formItemLayout}>
                {type === 'view'
                  ? `${model.validTimeStart}~${model.validTimeEnd}`
                  : getFieldDecorator('validTime', {
                      initialValue: [
                        moment(
                          model.validTimeStart === undefined ? moment() : model.validTimeStart,
                          'YYYY/MM/DD'
                        ),
                        moment(
                          model.validTimeEnd === undefined ? moment() : model.validTimeEnd,
                          'YYYY/MM/DD'
                        ),
                      ],
                      rules: [
                        {
                          required: true,
                          message: '有效期必填',
                        },
                      ],
                    })(
                      <RangePicker
                        defaultValue={[
                          moment(
                            model.validTimeStart === undefined ? moment() : model.validTimeStart,
                            'YYYY/MM/DD'
                          ),
                          moment(
                            model.validTimeEnd === undefined ? moment() : model.validTimeEnd,
                            'YYYY/MM/DD'
                          ),
                        ]}
                      />
                    )}
              </FormItem>
            </Col>
            {/*<Col {...colSpanLayout}>
              <FormItem label="抽奖状态" {...formItemLayout}>
                {type === 'view'
                  ? drawStatus[model.isOpenDraw]
                  : getFieldDecorator('isOpenDraw', {
                      initialValue: model.isOpenDraw === undefined ? 2 : model.isOpenDraw,
                      rules: [
                        {
                          required: true,
                          message: '抽奖状态必填',
                        },
                        rulesReg('number'),
                      ],
                    })(
                      <Select autocomplete="off">
                        <option value={1}>已开奖</option>
                        <option value={2}>未开奖</option>
                        <option value={3}>开奖中</option>
                      </Select>
                    )}
              </FormItem>
            </Col>*/}
          </Card>

          {/*奖品信息*/}
          {/* @todo 当添加的奖品够5个的时候隐藏添加按钮（或者提示不能添加奖品）  */}
          {type !== 'view' && (
            <Button
              type="primary"
              icon="plus"
              onClick={() => {
                let list = this.state.giftDataSources || [];
                // console.log(list);
                if (list.length >= 5) {
                  uiUtils.showAlert('奖品数量上限！奖品数量不能大于5个。');
                } else {
                  //打开前先清空表单
                  this.drawGiftForm.props.form.resetFields();
                  this.setState({
                    willSelectGiftVisible: true,
                  });
                }
              }}
              style={{ marginBottom: 20 }}
            >
              添加奖品
            </Button>
          )}
          <Card
            bordered
            hoverable
            size="small"
            bodyStyle={{ paddingBottom: 10 }}
            style={{ marginBottom: 20 }}
            title="奖品信息"
          >
            <Table
              pagination={false}
              columns={giftColumns}
              dataSource={this.state.giftDataSources}
              scroll={{ x: 670 }}
            />
          </Card>

          {/*抽奖活动介绍富文本*/}
          <Card
            bordered
            hoverable
            size="small"
            bodyStyle={{ paddingBottom: 10 }}
            style={{ marginBottom: 20 }}
            title="图文介绍"
          >
            <div>
              <BraftEditor
                extendControls={extendControls}
                className={styles.my_editor}
                {...editorProps}
                value={this.props.contentHtml}
                placeholder="请输入介绍"
                onChange={value => {
                  this.state.contentHtml = value;
                }}
              />
            </div>
          </Card>
        </Form>

        {/*添加礼品弹窗*/}
        <DrawGiftForm
          key={Math.random()}
          visible={this.state.willSelectGiftVisible}
          onCancel={() => {
            this.drawGiftForm.props.form.resetFields();
            this.setState({ willSelectGiftVisible: false });
          }}
          onOk={gift => {
            let datasources = this.state.giftDataSources;
            if (datasources === undefined) {
              datasources = [];
            }
            datasources.push(gift);
            this.setState({
              giftDataSources: datasources,
            });
            //这里保存审核结果
            this.setState({
              willSelectGiftVisible: false,
            });
          }}
          wrappedComponentRef={inst => {
            this.drawGiftForm = inst;
          }}
        />
      </Fragment>
    );
  }
}

EditForm = Form.create({})(EditForm);
